package com.gupaoedu.vip.pattern.springmvc2.aop;

import com.gupaoedu.vip.pattern.springmvc2.aop.intercept.MyMethodInvocation;
import com.gupaoedu.vip.pattern.springmvc2.aop.support.MyAdvisedSupport;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

public class MyJDKDaynamicAopProxy implements MyAopProxy, InvocationHandler {

    private MyAdvisedSupport advised;

    public MyJDKDaynamicAopProxy(MyAdvisedSupport config) {
        this.advised = config;
    }

    public Object getProxy() {
        return getProxy(this.advised.getTargetClass().getClassLoader());
    }

    public Object getProxy(ClassLoader classLoader) {
        return Proxy.newProxyInstance(classLoader,this.advised.getTargetClass().getInterfaces(),this);
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method,this.advised.getTargetClass());
        MyMethodInvocation methodInvocation = new MyMethodInvocation(proxy, this.advised.getTarget(), method, args, this.advised.getTargetClass(),chain );
        return methodInvocation.proceed();
    }
}
